import { createLogger, format, transports } from 'winston'
import MySQLTransport from 'winston-mysql'
import configData from '../config/sequelize'

const env = (process.env.NODE_ENV as Env) || 'development'

const getOptions = () => {
  const config = configData[env] as any
  if (config.url || config.use_env_variable) {
    const db_url = config.url || process.env[config.use_env_variable]
    const regex =
      /mysql:\/\/(?<user>.*?):(?<password>.*?)@(?<host>.*?):(?<port>\d+)\/(?<database>.*)/
    const match = db_url.match(regex)
    if (match) {
      const { user, password, host, database } = match.groups
      return {
        host,
        user,
        password,
        database,
        table: 'logs',
      }
    } else {
      console.log('Invalid database URL')
    }
  }
  return {
    host: config.host,
    user: config.username,
    password: config.password,
    database: config.database,
    table: 'logs',
  }
}

const logger = createLogger({
  level: 'info',
  format: format.combine(
    format.errors({ stack: true }), // 添加错误栈信息
    format.json(),
  ),
  defaultMeta: { service: 'dami_stu' },
  transports: [
    // new winston.transports.File({ filename: 'error.log', level: 'error' }),
    // new winston.transports.File({ filename: 'combined.log' }),
    new MySQLTransport(getOptions()), // 将日志写入mysql
  ],
})

if (process.env.NODE_ENV !== 'production') {
  logger.add(
    new transports.Console({
      format: format.combine(format.colorize(), format.simple()),
    }),
  )
}

export default logger
